/*
** By Qing Li 2017-06
*/
;
var vui = function(v) {
	
	var $v = {};  // 函数对象容器
	
	$v.imgUrl = '';
	
	// dom获取
	$v.getdom = function(ele) {
		if(ele == '') return;
		var ret;
		if(/([.])+/.test(ele)) {
			ret = document.querySelectorAll(ele);
		}else if(/([#])+/.test(ele)) {
			ret = document.querySelector(ele);
		}else if(/([.*])?/.test(ele)) {
			ret = document.querySelectorAll(ele);
		}
		return ret;
	}
	// 添加事件监听
	$v.addEvt = function(ele, event, callback) {
		if(ele) {
			return ele.addEventListener(event, callback, false);
		}
	}
	// 轮播图
	$v.swiper = function(opts) {
		var baseCg = {
			el: 'body',
			autoPlay: true,  // 是否开启自动轮播
			duration: 3000,  // 自动轮播时间间隔
			indicator: true,  // 是否显示指示器
		};
		var opts = typeof opts === 'object' ? extend(baseCg,opts) : baseCg;
		var	containerH = $v.getdom(opts.el).offsetWidth,
			innerH = (containerH >= window.innerWidth) ? window.innerWidth : containerH,  // 可视区高度
			inner = $v.getdom(opts.el + ' .inner'),
			item = $v.getdom(opts.el + ' .item'),
			itemL = item.length,
			prev = $v.getdom(opts.el + ' .prev')[0],
			next = $v.getdom(opts.el + ' .next')[0],
			prevW = nextW = prev.offsetWidth,
			ul = $v.getdom(opts.el + ' .list'),
			idt = null;
			autoplay = null;
// 						up = getdom(opts.el + ' .narrow .up'),
// 						dw = getdom(opts.el + ' .narrow .dw'),
			index = 0,
			totalOffset = innerH * index;
		/**
		 * @des 初始化
		 */
		function _init() {
			ul[0].style.left = totalOffset + 'px';
			inner[0].style.width = innerH + 'px';
			for(var i=0,l=item.length; i<l; i++) {
				item[i].style.width = innerH + 'px';
			}
			ul[0].style.width = (innerH * item.length) + 'px';
			
			dom(item);
			
			opts.indicator && indicator();
			
			new Swipe();
		}
		/**
		 * @des 继承函数
		 */
		function extend(son, child) {
			var child = typeof child === 'object' ? child : {};
			for(var k in child) {
				son[k] = child[k];
			}
			return son;
		}
		/**
		 * @des DOM树构建函数
		 */
		function Fragment(tagName, props, children) {
			this.tagName = tagName;
			this.props = props;
			this.children = children;
		}
		Fragment.prototype.render = function() {
			var fg = document.createDocumentFragment(),
				el = document.createElement(this.tagName),
				props = this.props,
				children = this.children || [];
			for(var p in props) {
				el.setAttribute(p, props[p]);
			}
			children.forEach(function(child) {
				var childEl = (child instanceof Fragment)
					? child.render()
					: document.createTextNode(child);
				el.appendChild(childEl);
			})
			fg.appendChild(el);
			return fg;
		}
		function el(tagName, props, children) {
			return new Fragment(tagName, props, children);
		}
		/**
		 * @des DOM树重构，以实现loop
		 */
		function dom(ele) {
			var tagName = ele[0].nodeName.toLowerCase(),
				props1 = {},
				props2 = {},
				children1 = [],
				children2 = [],
				attrArr1 = [].slice.call(ele[0].attributes),
				attrArr2 = [].slice.call(ele[ele.length - 1].attributes);
			attrArr1.forEach(function(item, i) {
				item.nodeName == 'class'
					? props1[item.nodeName] = item.nodeValue
					: props1[item.nodeName] = 'position: absolute; ' + item.nodeValue + ' left:'+ (innerH * itemL) +'px;';
			})
			attrArr2.forEach(function(item, i) {
				item.nodeName == 'class'
					? props2[item.nodeName] = item.nodeValue
					: props2[item.nodeName] = 'position: absolute; ' + item.nodeValue + ' left:-'+ innerH +'px;';
			})
			children1.push(ele[0].innerHTML);
			children2.push(ele[ele.length - 1].innerHTML);
			
			var eleLast = el(tagName, props1, children1).render();
			ul[0].appendChild(eleLast);
			var eleFirst = el(tagName, props2, children2).render();
			ul[0].insertBefore(eleFirst, item[0]);
		}
		
		/**
		 * @des 指示器
		 */
		function indicator() {
			var idtArr = [];
			
			for(var i=0,l=item.length; i<l; i++) {
				idtArr.push(el('li', {class: 'idt-i'}, []));
			}
			var ul = el('ul', {class: 'indicator'}, idtArr);
			var ulRoot = ul.render();
			inner[0].appendChild(ulRoot)
			
			idt = $v.getdom('#fullpage .indicator')[0];
			idt.children[index].classList.add('active');
		}
		function idtActive() {
			for(var i=0,l=idt.children.length; i<l; i++) {
				idt.children[i].classList.remove('active');
			}
			if(index >= idt.children.length) {
				idt.children[0].classList.add('active');
			}else {
				idt.children[index].classList.add('active');
			}
			
		}
		/**
		 * @des 滑动操作
		 */
		function Swipe() {
			var startY, moveY, endY, me = this;
			document.addEventListener('touchstart', function(e) {
				startY = e.changedTouches[0].pageX;
			}, false);
			document.addEventListener('touchmove', function(e) {
				moveY = e.changedTouches[0].pageX;
				h(startY, moveY);
			}, false);
			document.addEventListener('touchend', function(e) {
				endY = e.changedTouches[0].pageX;
				(Math.abs(endY - startY) >= 100) && y(startY, endY)
			}, false);
			idt && idt.addEventListener('click', function(e) {
				var oldIndex = index, newIndex;
				newIndex = [].slice.call(idt.children).indexOf(e.target);
				if(newIndex >= oldIndex) {
					index = newIndex-1;
					me.swipeU();
				}else if(newIndex < oldIndex) {
					index = newIndex+1;
					me.swipeD();
				}
			}, false);
			prev.addEventListener('click', function(e) {
				me.swipeD();
			}, false);
			next.addEventListener('click', function(e) {
				me.swipeU();
			}, false);
			opts.autoPlay == 1 ? autoPlay = setInterval(function() {
				me.swipeU();
			}, 3000) : autoPlay = null;
			function h(s,m) {
				if(m - s > 0) {
					me.swipeDown(m-s);
				}else {
					me.swipeUp(m-s);
				}
			}
			function y(s,e) {
				if(e - s < 0) {
					me.swipeU()
				}else {
					me.swipeD();
				}
			}
		}
		Swipe.prototype = {
			swipeUp(m) {
				if(index >= item.length-1) return;
				totalOffset = -innerH * index + m;
				ul[0].style.left = totalOffset + 'px';
				
			},
			swipeDown(m) {
				if(index === 0) return;
				totalOffset = -innerH * index + m;
				ul[0].style.left = totalOffset + 'px';
			},
			swipeU() {
				if(index >= item.length) {
					// ul归位
					index = 0;
					totalOffset = -innerH * index;
					ul[0].style.left = totalOffset + 'px';
				};
				
				index++;
				idt && idtActive();

				var timer = setInterval(function() {
					if(innerH * index + totalOffset <= 1) {
						totalOffset = -innerH*index;
						ul[0].style.left = totalOffset + 'px';
						clearInterval(timer);
						return;
					}else {
						totalOffset += -(innerH*index + totalOffset)/10;
						ul[0].style.left = totalOffset + 'px';
					}
				}, 20);
			},
			swipeD() {
				if(index === 0) {
					// ul归位
					index = 3;
					totalOffset = -innerH * index;
					ul[0].style.left = totalOffset + 'px';
				};
				index--;
				idt && idtActive();

				var timer = setInterval(function() {
					if(-totalOffset - innerH * index <= 1) {
						totalOffset = -innerH * index;
						ul[0].style.left = totalOffset + 'px';
						clearInterval(timer);
						return;
					}else {
						totalOffset += -(innerH*index + totalOffset)/10;
						ul[0].style.left = totalOffset + 'px';
					}
				}, 20);
			}
		}
		_init();
	}
	// 列表轮播
	$v.slider = function(setting) {
		var baseConfig = {
			el: '.slider',
			len: 1,
			click: 1,
			gap: 20,
			autoPlay: false,
			duration: 3000,
		};
		var setting = typeof setting === 'object' ? setting : {};
		var	opts = $v.extend(baseConfig, setting);
		var	prev = $v.getdom('.prev')[0],  // 上翻按钮
			next = $v.getdom('.next')[0],  // 下翻按钮
			inner = $v.getdom(opts.el+' .inner')[0],  // 可视区容器
			list = $v.getdom(opts.el+' .list')[0],  // 列表容器
			tW = $v.getdom(opts.el)[0].offsetWidth,  // 容器总宽度
			prevW = nextW = next.offsetWidth,  // 按钮宽度
			innerW = opts.click === 1 ? tW : (tW-prevW*2),  // 可视区宽度
			m = 0,  // 记录切换按钮点击次数
			iW = (opts.click === 1) ? ((innerW-(opts.len-1)*opts.gap) / opts.len) : ((innerW-(opts.len-1)*opts.gap) / opts.len),  // 单个item宽度
			leftCache = -iW * m,  // 左移距离缓存
			speed = (iW+opts.gap) / 5,  //  滑动速度
			player = null;
		
		inner.style.width = innerW + 'px';  // 可视容器
		list.style.width = (iW + opts.gap) * list.children.length + 'px';  // 列表项容器总宽度
		
		for(var i=0,l=list.children.length; i<l; i++) {
			list.children[i].style.width = iW + 'px';
			list.children[i].style.marginRight = opts.gap + 'px';
		}
		
		// 手动上翻切换
		$v.addEvt(prev, 'click', function() {
			prevPlay();
		})
		// 手动下翻切换
		$v.addEvt(next, 'click', function() {
			nextPlay();
		})
		// Prev
		function prevPlay() {
			if(m === 0) return;
			var totalLeft = leftCache - (leftCache / m);  // 本次点击需要偏移的距离
			m--;
			var timer = setInterval(function() {
				if(Math.ceil(leftCache) >= totalLeft) {
					clearInterval(timer);
					return;
				}
				list.style.left = leftCache + speed + 'px';
				leftCache += speed;
			}, 30)
		}
		// Next
		function nextPlay() {
			if(m >= list.children.length - opts.len) {
				list.style.left = 0 + 'px';
				m = -1;
				leftCache = 0;
			}
			m++;
			var totalLeft = (-iW - opts.gap) * m;  // 本次点击需要偏移的距离
			var timer = setInterval(function() {
				if(Math.ceil(-leftCache) >= -totalLeft) {
					clearInterval(timer);
					return;
				}
				list.style.left = leftCache + (-speed) + 'px';
				leftCache += (-speed);
			}, 30);
		}
		function autoPlay(isPlay) {
			player = setInterval(function() {
				nextPlay();
			}, opts.duration || 3000);
		}
		autoPlay(opts.autoPlay);
		// 鼠标悬停 停止播放
		$v.addEvt(inner, 'mouseenter', function() {
			clearInterval(player);
		})
		$v.addEvt(inner, 'mouseleave', function() {
			player = setInterval(function() {
				nextPlay();
			}, opts.duration || 3000);
		})
		$v.addEvt(prev, 'mouseenter', function() {
			clearInterval(player);
		})
		$v.addEvt(prev, 'mouseleave', function() {
			player = setInterval(function() {
				nextPlay();
			}, opts.duration || 3000);
		})
		$v.addEvt(next, 'mouseenter', function() {
			clearInterval(player);
		})
		$v.addEvt(next, 'mouseleave', function() {
			player = setInterval(function() {
				nextPlay();
			}, opts.duration || 3000);
		})
	}
	// 打开新页面
	$v.openWin = function(opts) {
		console.log(window.location);
		var opts = opts || {};
		var win = window, origin = win.location.origin, redirect = '', query = '', path = '', search = '', tmpArr = Object.keys(opts.params), k;
		path = opts.path ? opts.path : '';
		if(tmpArr.length > 0) {
			tmpArr = [];
			for(k in opts.params) {
				tmpArr.push(k + '=' + opts.params[k]);
			}
			search = '?'+tmpArr.join('&');
		}
		redirect = origin + path + search;
		console.log(redirect);
		win.location.href = redirect;
	}
	// 获取页面参数
	$v.pageParams = (function() {
		var search = window.location.search;
		var tmpArr = search.substr(1).split('&');
		var obj = {};
		tmpArr.forEach(function(item) {
			obj[item.split('=')[0]] = item.split('=')[1];
		})
		return obj;
	})();
	// 选项卡
	$v.navTab = function(opts) {
		var navTag = $v.getdom('#navTab').children;
		var i, j, l = navTag.length;
		if(opts.index) {
			for(j=0; j<l; j++) {
				navTag[j].classList.remove('active');
			}
			navTag[opts.index].classList.add('active');
		}
		for(i=0; i<l; i++) {
			$v.addEvt(navTag[i], 'click', function() {
				var index = this.getAttribute('data-indx');
				for(j=0; j<l; j++) {
					navTag[j].classList.remove('active');
				}
				this.classList.add('active');
				opts.next.call(this, index);
			})
		}
	}
	// 计数器
	$v.counter = function() {
		var dec = $v.getdom('.decrease');
		var inc = $v.getdom('.increase');
		var counter = 1;  // 计数器初始值
		$v.addEvt(dec[0], 'click', function() {
			if(counter <= 1) {
				return;
			}else {
				counter -= 1;
			}
			$v.getdom('#counter').value = counter;
		}, false);
		$v.addEvt(inc[0], 'click', function() {
			counter += 1;
			$v.getdom('#counter').value = counter;
		}, false);
	}
	
	// 返回前一个历史页面
	$v.goback = function() {
		var back = $v.getdom('.vui-back');
		var menu = $v.getdom('.vui-menu');
		if(back.length > 0) {
			$v.addEvt(back[0], 'click', function() {
				window.history.go(-1)
			});
		}
		if(menu.length > 0) {
			$v.addEvt(menu[0], 'click', function() {
				var html = '<div class="menu"></div>';
				var aside = document.createElement('div');
				aside.setAttribute('class', 'alert');
				document.body.appendChild(aside);
				$v.getdom('.alert')[0].innerHTML = html;
			})
		}
	}
	
	/* 弹窗msg */
	$v.msg = function(opts) {
		var html = "<div class='vui-msg' style='background-color:"+opts.bgColor+"'><span>"+ opts.msg +"</span></div>";
		var alert = document.createElement('div');
		var timer;
		var tag = $v.getdom('#vui-alert');
		alert.setAttribute('id', 'vui-alert');
		alert.innerHTML = html;
		if(!tag) {
			document.body.appendChild(alert);
		}else {
			return;
		}
		timer = setTimeout(function() {
			document.body.removeChild(alert);
			clearTimeout(timer);
			if(opts.next) {
				opts.next.call(this);
			}
		}, opts.duration || 2000);
		
	}
	
	/* 弹窗 alert */
	$v.alert = function(opts, cb) {
		var html, alert;
		var size = opts.size ? opts.size.split(',') : [300,200];
		var tag = $v.getdom('#vui-alert');
		if(!tag) {
			_createPopup();
		}else {
			return;
		}
		// 创建弹窗
		function _createPopup() {
			alert = document.createElement('div');
			html = "<div class='vui-alert'>\
						<h3>提醒</h3>\
						<div class='vui-alert-body' style='width:"+size[0]+"px;height:"+size[1]+"px;'>"+opts.msg+"</div>\
						<div class='vui-alert-button'>\
							<button type='button' class='vui-alert-btn sure'>确认</button>\
							<button type='button' class='vui-alert-btn cancel'>取消</button>\
						</div>\
						<div class='vui-alert-close'>\
							<svg viewBox='0,0,24,24'>\
								<path d='M6.5 6 L 17.5 17.5 M17.5 5.5 L 6.5 17.5' stroke='#666'></path>\
							</svg>\
						</div>\
					</div>\
				";
			alert.setAttribute('id', 'vui-alert');
			alert.innerHTML = html;
			document.body.appendChild(alert);
		}
		// 延时操作
		setTimeout(function(){
			var close = $v.getdom('.vui-alert-close');
			var sure = $v.getdom('.vui-alert-button button.sure');
			var cancel = $v.getdom('.vui-alert-button button.cancel');
			// 关闭弹窗
			_closePopup(close[0]);
			_closePopup(cancel[0]);
			function _closePopup(ele) {
				$v.addEvt(ele, 'click', function() {
					document.body.removeChild(alert);
				})
			}
			// 确认之后执行回调
			$v.addEvt(sure[0], 'click', function() {
				if(typeof cb == 'function') {
					document.body.removeChild(alert);
					return cb.call(this);
				}else {
					return;
				}
			})
		},0)
	}
	/* 弹窗 textarea */
	$v.txtArea = function(opts, cb) {
		var html, alert;
		var size = opts.size ? opts.size.split(',') : [300,200];
		var tag = $v.getdom('#vui-alert');
		if(!tag) {
			_createPopup();
		}else {
			return;
		}
		// 创建弹窗
		function _createPopup() {
			alert = document.createElement('div');
			html = "<div class='vui-alert'>\
						<h3>"+opts.title+"</h3>\
						<textarea class='vui-alert-body' style='width:"+size[0]+"px;height:"+size[1]+"px;' placeholder='"+opts.msg+"'></textarea>\
						<div class='vui-alert-button'>\
							<button type='button' class='vui-alert-btn sure'>确认提交</button>\
							<button type='button' class='vui-alert-btn cancel'>取消</button>\
						</div>\
						<div class='vui-alert-close'>\
							<svg viewBox='0,0,24,24'>\
								<path d='M6.5 6 L 17.5 17.5 M17.5 5.5 L 6.5 17.5' stroke='#666'></path>\
							</svg>\
						</div>\
					</div>\
				";
			alert.setAttribute('id', 'vui-alert');
			alert.innerHTML = html;
			document.body.appendChild(alert);
		}
		// 延时操作
		setTimeout(function(){
			var close = $v.getdom('.vui-alert-close');
			var sure = $v.getdom('.vui-alert-button button.sure');
			var cancel = $v.getdom('.vui-alert-button button.cancel');
			// 关闭弹窗
			_closePopup(close[0]);
			_closePopup(cancel[0]);
			function _closePopup(ele) {
				$v.addEvt(ele, 'click', function() {
					console.log(this)
					document.body.removeChild(alert);
				})
			}
			// 确认之后执行回调
			$v.addEvt(sure[0], 'click', function() {
				var txt = $v.getdom('textarea')[0].value || '';
				if(typeof cb == 'function') {
					document.body.removeChild(alert);
					return cb.call(this, txt);
				}else {
					return;
				}
			})
		},0)
	}
	/* extend */
	$v.extend = function(base, opts) {
		base = typeof base == 'object' ? base : {};
		opts = typeof opts == 'object' ? opts : {};
		for(var key in opts) {
			base[key] = opts[key];
		}
		return base;
	};
	/* ajax */
	$v.ajax = function(opts) {
		var baseConfig = {
			type: "GET",
			error: function(e) {}
		};
		var config = opts || {};
		config = $v.extend(baseConfig, config);
		var xhr = new XMLHttpRequest();
		var ret;
		var async = 'async' in config ? config.async : true;
		var protocol = /^([\w-]+:)\/\//.test(config.url) ? RegExp.$1 : window.location.protocol;
		xhr.onreadystatechange = function() {
			if(xhr.readyState === 4) {
				var isLocal = protocol === 'file:';
				if((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || (xhr.status === 0 && isLocal && xhr.responseText)) {
					ret = xhr.responseText;
					try {
						if(config.dataType == 'xml') {
							ret = xhr.responseXML;
						}else if(config.dataType == 'json') {
							ret = JSON.parse(xhr.responseText);
						}
						config.success.call(null, ret, 'success~', xhr)
					}catch(e) {
						config.error.call(null, e, 'parsererror~', xhr)
					}
				}else {
					config.error.call(xhr.statusText, 'error~', xhr)
				}
			}
			
		}
		var tmpArr = [];
		for(var key in config.data) {
			tmpArr.push(encodeURIComponent(key) + '=' + encodeURIComponent(config.data[key]));
		}
		config.data = tmpArr.join('&');
		xhr.open(config.type.toUpperCase(), config.url, async, config.username, config.password);
		xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
		xhr.setRequestHeader('Accept', 'application/json');
		xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xhr.timeout = config.timeout || 0;
		xhr.send(config.data ? config.data : null);
		return xhr;
	}
	/* 划动加载 */
	$v.swipeLoad = function(opts) {
		var config = opts || {};
		if(config.type == 'upLoad') {  // 上划加载
			var startY, _this = this;
			document.addEventListener('touchstart', function(e) {
				startY = e.changedTouches[0].pageY;
			}, false);
			document.addEventListener('touchend', function(e) {
				if(e.changedTouches[0].pageY > startY-30) {
					return;
				}else {
					config.next.call(null);
				}
			}, false);
		}
	}
	/* 日期时间 */
	$v.dateTime = function(tm, format) {
		if(tm == '') return;
		var format = format || 'yy-mm-dd h:m:s', time = '';
		var t = new Date(tm*1000);
		var ad = function(val) {
			if(val == '') return;
			return val < 10 ? ('0' + val) : val;
		};
		var y = t.getFullYear(), m = ad(t.getMonth()+1), d = ad(t.getDate()), h = ad(t.getHours()), mi = ad(t.getMinutes()), s = ad(t.getSeconds());
		switch(format) {
			case 'yy-mm-dd': 
				time = y+'-'+m+'-'+d;
				break;
			case 'h:m:s':
				time = h+':'+mi+':'+s;
				break;
			case 'yy-mm-dd h:m:s':
				time = y+'-'+m+'-'+d+' '+h+':'+mi+':'+s;
				break;
			default:
				time = y+'-'+m+'-'+d+' '+h+':'+mi+':'+s;
				break;
		}
		return time;
	}
	
	/* 本地缓存 */
	$v.setCookie = function(key, val, exdays) {
		var d = new Date();
		d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
		document.cookie = key + "=" + escape(val) + ";expires=" + d.toGMTString() + ";path=/";
	}
	$v.getCookie = function(key) {
		var key = key+'=';
		var cookies = document.cookie.split(';');
		for(var i=0,l=cookies.length; i<l; i++) {
			var coo = cookies[i].trim();
			if(coo.indexOf(key)==0) return coo.substring(key.length, coo.length);
		}
		return '';
	}
	$v.rmCookie = function(key) {
		var d = new Date();
		d.setTime(d.getTime() - (9 * 60 * 60 * 1000));
 		document.cookie = key + "=;expires=" + d.toGMTString() + ";path=/";
	}
	$v.setStorage = function(key, val) {
		window.localStorage.setItem(key, JSON.stringify(val));
	};
	$v.getStorage = function(key) {
		var val = JSON.parse(window.localStorage.getItem(key));
		return val;
	};
	$v.rmStorage = function(key) {
		window.localStorage.removeItem(key);
	}
	/* 单例模式 */
	$v.single = function(fn) {
		var ret;
		return function() {
			return ret || (ret = fn.apply(this, arguments));
		};
	}
	// 获取用户信息的地方，首先使用此方法，验证用户是否在登录状态
	$v.isLogin = function() {
		var token = $v.getCookie('vui_logintoken'); // 登录Token
		if(!!token) {
			$v.ajax({
				url: '/api/',
				data: {},
				type: 'post',
				dataType: 'json',
				success: function(ret) {
					if(ret.stat == 1) {
						$v.setStorage('uinfo', ret.data);
					}else {
						$v.rmStorage('uinfo');
					}
				}
			})
		}else {
			$v.rmStorage('uinfo');
		}
	}
	$v.logout = function() {
		$v.rmCookie('vui_logintoken');
		$v.rmStorage('uinfo');
		if(!$v.getCookie('vui_logintoken') && !$v.getStorage('uinfo')) {
			$v.msg({
				msg: '退出成功~',
				next: function() {
					window.location.href = '/';
				}
			})
		}
		
	}
	// 渲染当前页按钮
	// (function() {
		var tabs = window.parent.document.links, curIndex = $v.pageParams.navId;
		for(var i=0,l=tabs.length; i<l; i++) {
			tabs[i].classList.remove('active');
			if(tabs[i].dataset.indx == curIndex) {
				tabs[i].classList.add('active');
			}
		}
		
	// })();
	
	v.v = $v;  // 对象赋值给
	
	return;

};

